package uzpay

import (
	"context"
	"fmt"
	"time"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/pay/base"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/uzpay/uzpay"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &Uzpay{
		Url:        config.Url,
		MerchantId: config.MerchantId,
		SecretKey:  config.SecretKey,
		NotifyUrl:  config.NotifyUrl,
		AppId:      config.AppId,
	}
}

type Uzpay struct {
	MerchantId string
	NotifyUrl  string
	SecretKey  string
	Url        string
	AppId      string
}

type Resp struct {
	Code      string `json:"code"`
	Timestamp int64  `json:"timestamp"`
	Message   string `json:"message"`
	Params    data   `json:"params"`
}
type data struct {
	MerchantRef  string `json:"merchant_ref"`
	SystemRef    string `json:"system_ref"`
	Amount       string `json:"amount"`
	Fee          string `json:"fee"`
	Status       int    `json:"status"`
	SuccessTime  int    `json:"success_time"`
	Payurl       string `json:"payurl"`
	ExtendParams string `json:"extend_params"`
	Product      string `json:"product"`
}

// 代收订单创建
func (uz *Uzpay) Pay(ctx context.Context, req map[string]any) (resp base.PayResponse, err error) {
	tempParams := make(map[string]any)
	tempParams["url"] = uz.Url + "/pay/web"
	tempParams["mid"] = uz.MerchantId
	tempParams["orderID"] = req["orderNo"]
	tempParams["NotifyUrl"] = uz.NotifyUrl
	tempParams["payType"] = uz.AppId
	tempParams["amount"] = fmt.Sprintf("%.2f", req["amount"])
	tempParams["orderDate"] = time.Now().Format("2006-01-02 15:04:05")
	tempParams["SecretKey"] = uz.SecretKey
	if _, exists := req["bankCode"]; exists {
		tempParams["bankCode"] = req["bankCode"]
	}
	if _, exists := req["goodsName"]; exists {
		tempParams["goodsName"] = req["goodsName"]
	}
	if _, exists := req["payerEmail"]; exists {
		tempParams["payerEmail"] = req["payerEmail"]
	}
	if _, exists := req["payerName"]; exists {
		tempParams["payerName"] = req["payerName"]
	}
	if _, exists := req["payerPhone"]; exists {
		tempParams["payerPhone"] = req["payerPhone"]
	}
	if _, exists := req["payerCard"]; exists {
		tempParams["payerCard"] = req["payerCard"]
	}
	payResult, err := uzpay.UzPay(tempParams)
	if err != nil {
		return resp, err
	}
	resp = base.PayResponse{
		Url:     payResult.PayInfo,
		OrderNo: payResult.MchOrderNo,
	}
	return resp, nil

}
